package com.ran.providermodule.provider;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import java.util.List;

import static com.ran.providermodule.provider.ContentData.UserTableData.CONTENT_URI;

/**
 * Created by ran on 2017/10/21.
 */

public class ProviderDao implements ProviderInsert, ProviderQuery {
    private static final String TAG = ProviderDao.class.getSimpleName();

    private static ContentResolver contentResolver;
    private static volatile ProviderDao mInstance;

    private ProviderDao() {
    }

    public static ProviderDao getInstance(Context context) {
        if (mInstance == null) {
            synchronized (ProviderDao.class) {
                if (mInstance == null) {
                    mInstance = new ProviderDao();
                }
            }
        }
        contentResolver = context.getContentResolver();
        return mInstance;
    }

    @Override
    public void insert(ContentValues contentValues) {
        Uri uri = contentResolver.insert(CONTENT_URI, contentValues);
        Log.d(TAG, uri.toString());
    }

    @Override
    public void batchInsert(List<ContentValues> contentValuesList) {
        ContentValues[] contentValues = new ContentValues[contentValuesList.size()];
        for (int i = 0; i < contentValuesList.size(); i++) {
            contentValues[i] = contentValuesList.get(i);
        }
        int count= contentResolver.bulkInsert(CONTENT_URI, contentValues);
        Log.d(TAG, "count is : "+count);
    }

    @Override
    public void query() {
        String columns[] = new String[]{ContentData.UserTableData.TITLE, ContentData.UserTableData.NAME, ContentData.UserTableData.DATE_ADDED, ContentData.UserTableData.SEX};
        Cursor cursor = contentResolver.query(CONTENT_URI, columns, null, null, null);
        try {
            if (cursor.moveToFirst()) {
                String title = null;
                String name = null;
                do {
                    title = cursor.getString(cursor.getColumnIndex(ContentData.UserTableData.TITLE));
                    name = cursor.getString(cursor.getColumnIndex(ContentData.UserTableData.NAME));
                    Log.d(TAG, "title: " + title + " \n name:" + name + " cursor count: " + cursor.getCount());
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }
    }
}
